# def isValide(s):
#     stack = []
#     dic = {')': '(', ']': '[', '}': '{'}
#     for v in s:
#         if v == ('(' or '[' or '{'):
#             stack.append(v)
#         else:
#             tmp = stack.pop()
#             if dic[v] != tmp:
#                 return False
#     return True
#
# print(isValide('(]'))
#错误总结：
    # 1.在涉及到可能越界（pop,[-1]的情况下，不要放到else里。
    # 2.注意字典映射的用法。


def isValide(s):
    stack = []
    dic = {')': '(', ']': '[', '}': '{'}
    for v in s:
        # if v == ('(' or '[' or '{'):
        #     stack.append(v)
        # else:
        #     tmp = stack.pop()
        #     if dic[v] != tmp:
        #         return False
        if v in dic:
            tmp = stack.pop()   # 涉及到pop还是要在前面加限制条件
            if dic[v] != tmp:
                return False
        else:
            stack.append(v)
    return True         # 考虑不全面这里

# 正确解法
def isValide(s):
    stack = []
    dic = {')': '(', ']': '[', '}': '{'}
    for v in s:
        # if v == ('(' or '[' or '{'):
        #     stack.append(v)
        # else:
        #     tmp = stack.pop()
        #     if dic[v] != tmp:
        #         return False
        if v in dic and stack:
            tmp = stack.pop()
            if dic[v] != tmp:
                return False
        else:
            stack.append(v)
    return not stack

# 官方解答：更符合一般的思路编程题一个要提前想好步骤，不应该一股脑的上

class Solution:
    def isValid(self, s: str) -> bool:
        if len(s) % 2 == 1:  # 少做循环
            return False

        pairs = {
            ")": "(",
            "]": "[",
            "}": "{",
        }
        stack = list()
        for ch in s:
            if ch in pairs:
                if not stack or stack[-1] != pairs[ch]: # 少做两个循环
                    return False
                stack.pop()
            else:
                stack.append(ch)

        return not stack

